package ask.speedy;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import speedy.ask.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import ask.speedy.basic.BasicNode;
import ask.speedy.util.Constant;
import ask.speedy.util.ContainerParser;
import ask.speedy.util.RequestServer;
import ask.speedy.util.XMLParser;

public class TanyaSpeedyActivity extends Activity {
	
	private final int MENU_TUTORIAL = 0;
	private final int MENU_UPDATE = 1;
	private final int MENU_HELP = 2;
	private XMLParser xmlparser;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        this.requestWindowFeature(Window.FEATURE_NO_TITLE); // (NEW)
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN); // (NEW)
        
        setContentView(R.layout.main);
        
        Button startTanya = (Button)findViewById(R.id.startbt_tanyaspeedy);
        
        startTanya.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if (ContainerParser.tree != null) {
					Intent myintent = new Intent(getApplicationContext(), QuestionActivity.class);
					startActivity(myintent);
				}
			};
		});
        
        ProgressDialog progress = new ProgressDialog(this);
		progress.setMessage("Inisialisasi data...");
		new MyTask(progress, false, true).execute();
    }
    
    
    @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	
	/***
	 * create custom option menu
	 */
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_TUTORIAL, 0, getResources().getText(R.string.tutorial))
		.setIcon(R.drawable.setting);
		menu.add(0, MENU_UPDATE, 0, getResources().getText(R.string.update))
		.setIcon(R.drawable.refresh);
		menu.add(0, MENU_HELP, 0, getResources().getText(R.string.help))
		.setIcon(R.drawable.info);
        return true;
    }
	
	/***
     * Handles item selections on custom option menu
     */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
	        case MENU_TUTORIAL:
	        	Intent tutorial = new Intent(TanyaSpeedyActivity.this, TutorialActivity.class);
	        	startActivity(tutorial);
	        	return true;
	        case MENU_UPDATE:
	        	
	        	final ProgressDialog progress = new ProgressDialog(TanyaSpeedyActivity.this);
	    		progress.setMessage("Memperbarui basis pengetahuan...");
	        	
				final AlertDialog.Builder alert = new AlertDialog.Builder(this);
				alert.setTitle("Apakah Anda ingin mengupdate resource gambar pada aplikasi?");
				alert.setCancelable(false);
				alert.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
			    		new MyTask(progress, true, true).execute();
					}
				});
				alert.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
			    		new MyTask(progress, true, false).execute();
					}
				});
				
				alert.show();
	    		
	    		return true;
	        case MENU_HELP:
	        	Intent intent = new Intent(TanyaSpeedyActivity.this, HelpActivity.class);
	        	startActivity(intent);
	        	return true;
        }
        
        return false;
    }
	
	/***
	 * asynctask to do downloading map and preparing data
	 * @author passa
	 *
	 */
	public class MyTask extends AsyncTask<Void, Void, Void> {

		private ProgressDialog progress;
		private boolean isUpdating;
		private boolean updateImage;
		
		  public MyTask(ProgressDialog progress, boolean isUpdating, boolean updateImage) {
		    this.progress = progress;
		    this.isUpdating = isUpdating;
		    this.updateImage = updateImage;
		  }

		  public void onPreExecute() {
		    progress.show();
		  }

		  @Override
			protected Void doInBackground(Void... params) {
				// TODO Auto-generated method stub
			  	
			  	boolean updatedfile = false;
			  
			  	File file = new File(Constant.LOCAL_XML_PATH + Constant.XML_FILENAME);
			  	if (!file.exists() || isUpdating) {
			  		//if file doesnt exist or if it is time to updating
			  		RequestServer.DownloadFromURL(Constant.XML_URL, Constant.LOCAL_XML_PATH, Constant.XML_FILENAME);
			  		updatedfile = true;
			  	}
			  	
			  	File file_tutorial = new File(Constant.LOCAL_XML_PATH + Constant.TUTORIAL_FILENAME);
			  	if (!file_tutorial.exists() || isUpdating) {
			  		//if file doesnt exist or if it is time to updating
			  		RequestServer.DownloadFromURL(Constant.TUTORIAL_URL, Constant.LOCAL_XML_PATH, Constant.TUTORIAL_FILENAME);
			  	}
			  	
			  	xmlparser = new XMLParser();
				xmlparser.parseXML();
				
				if (updatedfile) {
					if (updateImage) {
						BasicNode basicNode = ContainerParser.tree;
						if (basicNode != null) {
							//updating image
							Map<String, Integer> listImage = new HashMap<String, Integer>();
							updateImage(basicNode, listImage); 
							
							//iterating over keys only
							for (String key : listImage.keySet()) {
								RequestServer.DownloadFromURL(Constant.URL_IMAGE_PATH + key, Constant.LOCAL_IMAGE_PATH, key);
							}
						}
					}
				}
				
					
			  	return null;
			}

		  public void onPostExecute(Void unused) {
		    progress.dismiss();
		  }
	}
	
	public void updateImage(BasicNode nodes, Map<String, Integer> listImage) {
		
		String imageName = nodes.getUrlImage();
		if (!imageName.equals("")) {
			//download image
			listImage.put(imageName, 1);
		}
		
		Map<String, BasicNode> childNodes = nodes.getChilds();
		
		Iterator<Map.Entry<String, BasicNode>> entries = childNodes.entrySet().iterator();
		while (entries.hasNext()) {
		    Map.Entry<String, BasicNode> entry = entries.next();
		    updateImage(entry.getValue(), listImage);
		}
	}
	
}